<?
/**
 * Copyright 2007 Melange.
 *
 * This file is part of PHP-MELANGE.
 *
 * PHP-MELANGE is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * PHP-MELANGE is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with PHP-MELANGE; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * @category    Melange
 * @package     php-melange
 * @subpackage  cms
 * @copyright   Copyright (c) 2007 Jeroen Simons. All rights reserved
 * @author      Jeroen Simons <jeroen@melange.nl>
 * @link        http://www.melange.nl/
 *
 */

require_once("cms/core/action/AbstractListAction.php");
require_once("cms/menu/om/MenuItemPeer.php");
require_once("cms/menu/om/MenuItemI18nPeer.php");

class ListAction extends AbstractListAction {

    private $log;

    public function __construct() {
        $this->log =& LoggerManager::getLogger("ListAction");
    }

    public function execute(ActionConfig &$mapping, &$form, Request &$request,
        Response &$response) {

        if(strlen($form->getId()) == 0)
            return $mapping->findForward("notfound");

        return parent::execute($mapping, $form, $request, $response);

    }

    public function activate(ActionConfig &$mapping, &$form, Request &$request, Response &$response) {

        $this->log->debug("Activating menu_items");
        $c = new Criteria();
        $c->add(MenuItemI18nPeer::MENU_ITEM_I18N_ID, $form->getItems(), Criteria::IN);
        $c->add(MenuItemI18nPeer::ACTIVE, true);
        try {
            MenuItemI18nPeer::doUpdate($c);
            $this->messages->add(ActionMessage::GLOBAL_MESSAGE,
                new ActionMessage("list.success.activate", true));
            $this->clearCache();
        } catch(PropelException $e) {
            $this->errors->add(ActionMessage::GLOBAL_MESSAGE,
                new ActionMessage("list.error.activate", true));
            $this->log->error($e->getMessage());
        }

    }

    public function deactivate(ActionConfig &$mapping, &$form, Request &$request, Response &$response) {

        $this->log->debug("Deactivating menu items");
        $c = new Criteria();
        $c->add(MenuItemI18nPeer::MENU_ITEM_I18N_ID, $form->getItems(), Criteria::IN);
        $c->add(MenuItemI18nPeer::ACTIVE, false);
        try {

            MenuItemI18nPeer::doUpdate($c);
            $this->messages->add(ActionMessage::GLOBAL_MESSAGE,
                new ActionMessage("list.success.deactivate", true));
            $this->clearCache();

        } catch(PropelException $e) {
            $this->errors->add(ActionMessage::GLOBAL_MESSAGE,
                new ActionMessage("list.error.deactivate", true));
            $this->log->error($e->getMessage());
        }

    }

    public function delete(ActionConfig &$mapping, &$form, Request &$request, Response &$response) {

        $this->log->debug("Deleting menu items");

        $c = new Criteria();
        $c->add(MenuItemI18nPeer::MENU_ITEM_I18N_ID, $form->getItems(), Criteria::IN);

        $conn = Propel::getConnection();

        try {

            $conn->begin();

            $menuItemI18ns = MenuItemI18nPeer::doSelectJoinMenuItem($c);
            foreach($menuItemI18ns as $menuItemI18n) {

                // Delete the page itself
                if($menuItemI18n->getLanguageCode() ==
                        $request->getContext()->getInitParameter(_Core::DEFAULT_LANGUAGE)) {

                    $menuitem = $menuItemI18n->getMenuItem();

                    // Move all higher positions one up.
                    $query =
                    "UPDATE menu_item SET position = position - 1 ".
                    "WHERE ".
                    "parent_id".(is_null($menuitem->getParentId()) ? " IS NULL" : " = ".$menuitem->getParentId())." ".
                    "AND menu_id = " .$menuitem->getMenuId()." ".
                    "AND position > " . $menuitem->getPosition();

                    $stmt = $conn->createStatement();
                    $stmt->executeUpdate($query, $conn);

                    // Delete the Page and have the onDelete=cascade take care of the rest.
                    MenuItemPeer::doDelete($menuitem, $conn);

                } else {



                    // Just this row.
                    MenuItemI18nPeer::doDelete($menuItemI18n->getMenuItemI18nId(), $conn);
                }
            }

            $this->messages->add(ActionMessage::GLOBAL_MESSAGE,
                new ActionMessage("list.success.delete", true));

            $conn->commit();

            $this->clearCache();

        } catch(PropelException $e) {
            $conn->rollback();
            $this->errors->add(ActionMessage::GLOBAL_MESSAGE,
                new ActionMessage("list.error.delete", true));
            $this->log->error($e);
        }

    }

    public function moveup(ActionConfig &$mapping, &$form, Request &$request,
            Response &$response) {
        $this->move($form, "up");
    }

    public function movedown(ActionConfig &$mapping, &$form, Request &$request,
            Response &$response) {
        $this->move($form, "down");
    }

    private function move($form, $direction) {

        $items = $form->getItems();

        $menuitemI18n = MenuItemI18nPeer::retrieveByPk($items[0]);
        $menuitem = $menuitemI18n->getMenuItem();

        if(is_null($menuitem)) {
            $this->errors->add(ActionMessage::GLOBAL_MESSAGE, new ActionMessage("Error finding menu item."));
            return;
        }

        $conn = Propel::getConnection();
        $stmt = $conn->createStatement();

        try {

            $conn->begin();

            $query =
                "UPDATE menu_item SET position = position ".($direction == "down" ? "-" : "+")." 1 ".
                "WHERE ".
                "parent_id".(is_null($menuitem->getParentId()) ? " IS NULL" : " = ".$menuitem->getParentId())." ".
                "AND position = ".($direction == "down" ? $menuitem->getPosition() + 1 : $menuitem->getPosition() - 1);

            $stmt->executeUpdate($query, $conn);

            $query =
                "UPDATE menu_item SET position = position ".($direction == "down" ? "+" : "-")." 1 ".
                "WHERE ".
                "parent_id".(is_null($menuitem->getParentId()) ? " IS NULL" : " = ".$menuitem->getParentId())." ".
                "AND menu_item_id = ".$menuitem->getMenuItemId();

            $stmt->executeUpdate($query, $conn);

            $conn->commit();

            $this->clearCache();

        } catch(PropelException $e) {
            $conn->rollback();
            $errors->add(ActionMessage::GLOBAL_MESSAGE,
                new ActionMessage("list.error.move", true));
            $this->log->error($e->getMessage());
        }

    }

    private function clearCache() {

        // Clear the menu cache
        require_once 'Zend/Cache.php';
        $cache = Zend_Cache::factory('Output', 'File', array(), array('cache_dir' => BASEPATH . "/_cache/"));
        $cache->clean(Zend_Cache::CLEANING_MODE_MATCHING_TAG, array('menu'));

    }

}
?>